package com.ry.chat.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

public class ChatClient {

    public static void main(String[] args) {
        ChatClient chatClient = new ChatClient();
        chatClient.client();
    }

    public void client() {
        EventLoopGroup eventExecutors = new NioEventLoopGroup(1);
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventExecutors);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ch.pipeline().addLast("stringDecoder", new StringDecoder());
                ch.pipeline().addLast("stringEncoder", new StringEncoder());
                ch.pipeline().addLast(new ClientChannelHandler());

            }
        });
        ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 8081);
        Channel channel = channelFuture.channel();

        assert false;

        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String s = scanner.nextLine();
            System.out.println("接入输入:" + s);
//            ByteBuf byteBuf= Unpooled.buffer(s.length());
//            byteBuf.writeBytes(s.getBytes());
//            channel.writeAndFlush(byteBuf);
            channel.writeAndFlush(s);
        }
    }
}
